package com.dnapipeline.modelManage.controller;

import com.dnapipeline.modelManage.entity.DeviceModel;
import com.dnapipeline.modelManage.service.DeviceService;
import com.dnapipeline.modelManage.entity.ProfileModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/v1/devices")
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    // 获取设备列表
    @GetMapping
    public ResponseEntity<List<DeviceModel>> getAllDevices(){
        List<DeviceModel> devices = deviceService.findAll();
        return ResponseEntity.ok(devices);
    }

    // 创建设备，自动生成deviceKey
    @PostMapping
    public ResponseEntity<DeviceModel> createDevice(@RequestBody DeviceModel device){
        DeviceModel created = deviceService.create(device);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }

    // 获取单个设备
    @GetMapping("/{deviceKey}")
    public ResponseEntity<DeviceModel> getDevice(@PathVariable String deviceKey){
        return deviceService.findById(deviceKey)
            .map(device -> ResponseEntity.ok(device))
            .orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).build());
    }

    // 更新设备（全量更新）
    @PutMapping("/{deviceKey}")
    public ResponseEntity<DeviceModel> updateDevice(@PathVariable String deviceKey,
                                                    @RequestBody DeviceModel deviceDetails){
        DeviceModel updated = deviceService.update(deviceKey, deviceDetails);
        if(updated != null){
            return ResponseEntity.ok(updated);
        }
        return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    }

    // 删除设备，级联删除关联的ProfileModel
    @DeleteMapping("/{deviceKey}")
    public ResponseEntity<String> deleteDevice(@PathVariable String deviceKey){
        deviceService.delete(deviceKey);
        return ResponseEntity.ok("Device deleted successfully");
    }

}